from rest_framework import serializers
from certificate_manager.models import User, Department
from django.contrib.auth import authenticate

# 现在Department对象需要通过url指定，我们希望其是动态的，至少现在不同步
# 优化指南：https://www.django-rest-framework.org/api-guide/serializers/#dynamically-modifying-fields
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['pk', 'uid', 'name', 'head', 'department', 'telephone', 'email', 'usertag_set']

    def to_representation(self, user):
        # 我们要修改usertag_set字段为中文名称+id的dict
        repr =  super().to_representation(user)
        repr['usertag_set'] = [{ 'pk': tag.pk, 'name': tag.name } for tag in user.usertag_set.all()]
        return repr


class AuthUserSerializer(serializers.Serializer):
    uid = serializers.CharField(max_length=20)
    password = serializers.CharField(max_length=50)

    def validate(self, attrs):
        user = authenticate(uid=attrs['uid'], password=attrs['password'])
        if user is None:
            raise serializers.ValidationError('uid or password error')
        return user

class CertJoinUserSerializer(serializers.Serializer):
    department = serializers.IntegerField()
    uid = serializers.CharField(max_length=20)

    def validate(self, attrs):
        user = User.objects.get(uid=attrs['uid'])
        department = Department.objects.get(pk=attrs['department'])

        cur_check_department = user.department
        while cur_check_department.nested_department:
            if department == cur_check_department:
                return attrs
            cur_check_department = cur_check_department.nested_department

        raise serializers.ValidationError(f'user [{user.uid}] not in department [{department.pk}].')

